<script  lang="ts">
import { useThrottleFn } from '@peng_kai/kit/libs/vueuse';
import CommissionShare from './CommissionShare.vue';

export const setCommissionPopup = useAntdModal(
  // eslint-disable-next-line import/no-self-import
  defineAsyncComponent(() => import('./SetCommission.vue')),
  {
    title: computed(() => $t('bqB6ysptp27geoIh9gz_9')),
    wrapClassName: 'ant-cover__Modal-drawer',
    centered: true,
    footer: null,
  },
);
</script>

<script setup lang="ts">
const props = defineProps<{
  userId: string;
}>();
const emits = defineEmits<{
  close: [];
}>();

const userCommissionQry = useQuery({
  queryKey: [apis.apiInviteUserCommissionsRates.id, toRef(props, 'userId')],
  queryFn: () => apis.apiInviteUserCommissionsRates({ id: props.userId! }),
});
const commissionsRates = ref<Api.GetData<typeof apis.apiInviteUserCommissionsRates>>();
watch(userCommissionQry.data, (data) => {
  if (data)
    commissionsRates.value = data.map(item => ({ ...item }));
}, { immediate: true });

const saveCommissionMut = useMutation({
  mutationKey: [apis.apiInviteUpdateUserCommissionsRates.id],
  mutationFn: apis.apiInviteUpdateUserCommissionsRates.setDefaultConfig({
    successMessage: $t('lvU2c6GcuuHaSr8vj853'),
  }),
});
const loading = computed(() => userCommissionQry.isLoading.value || saveCommissionMut.isPending.value);

const save = useThrottleFn(async () => {
  if (!commissionsRates.value)
    return;

  await saveCommissionMut.mutateAsync({ requestBody: {
    id: props.userId,
    commissions_rates: commissionsRates.value,
  } });
  emits('close');
}, 500);
</script>

<template>
  <div>
    <!-- 分成比例 -->
    <TCard class="mb-45" icon="i-local:compaign_3" :title="$t('bblXesmCulWv0GyYrU4Gy')">
      <TSuspenseView
        v-bind="buildSvPropsOfQuery(userCommissionQry)"
        class="grid grid-cols-2 gap-2" nonSuccessClass="col-span-full !p0"
      >
        <CommissionShare
          v-for="item of commissionsRates" :key="item.category_id"
          v-model:value="item.commissions" class="last:odd:col-span-2"
          :class="{ 'op-50 pointer-events-none': loading }"
          :minCommission="item.min_commissions" :maxCommission="item.max_commissions"
          :name="item.game_name" :coefficient="item.coefficient"
        />
      </TSuspenseView>
    </TCard>

    <AButton
      class="ant-cover__Button-3d-primary w-full"
      type="primary" :disabled="loading" :loading="loading"
      @click="save"
    >
      {{ $t('dqcvMmkkLelXhEb_6QHcN') }}
    </AButton>
  </div>
</template>
